<?php
/**
 * Created by PhpStorm.
 * User: 海峡
 * Date: 2021/1/11
 * Time: 14:14
 */
set_time_limit(0);//永不超时 使用cli 不能使用Nginx apache
include __DIR__ . '/function.php';
require __DIR__ . '/vendor/autoload.php';
use QL\QueryList;
$rang = range(1,2);

$dbms='mysql';     //数据库类型
$host='139.199.75.240'; //数据库主机名
$dbName='zfw';    //使用的数据库
$user='zfw';      //数据库连接用户名
$pass='DdB3S3X5bCb62kHJ';          //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";


try {
    $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
    echo "连接成功<br/>";
    /*你还可以进行一次搜索操作
    foreach ($dbh->query('SELECT * from FOO') as $row) {
        print_r($row); //你可以用 echo($GLOBAL); 来看到这些值
    }
    */
    $dbh = null;
} catch (PDOException $e) {
    die ("Error!: " . $e->getMessage() . "<br/>");
}
//默认这个不是长连接，如果需要数据库长连接，需要最后加一个参数：array(PDO::ATTR_PERSISTENT => true) 变成这样：
$db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));

foreach ($rang as $page){
    $url = 'https://news.ke.com/cs/baike/033/pg'.$page.'/';
    $html = http_request($url);
        //分析采集到的内容
    $datalist = QueryList::Query($html,[
        'pic'=>['.lj-lazy','data-original','',function($item){
        //得到扩展名
            $ext = pathinfo($item,PATHINFO_EXTENSION);
            //生成文件名
            $filename = md5($item).'_'.time().'.'.$ext;
            //生成本地路径
            $filepath = dirname(__DIR__).'/public/uploads/article/'.$filename;
            file_put_contents($filepath,http_request($item));
            return '/uploads/article/'.$filename;
        }],
        'title'=>['.item .text .LOGCLICK','text'],
        'desn'=>['.item .text .summary','text'],
        'url'=>['.item .text > a','href']
    ])->data;
}
//入库
foreach ($datalist as $val){
//    var_dump($val);
//    extract($val);
    //添加sql预处理
    $sql = "insert into zfw_articles (title,desn,pic,url,body) value (?,?,?,?,'')";
//    echo "insert into zfw_articles (title,desn,pic,url,body) value ('$title','$desn','$pic','$url')";

    $stmt = $db->prepare($sql);
    //var_dump($stmt);
    //入库
    $stmt->execute([$val['title'],$val['desn'],$val['pic'],$val['url']]);
}

//var_dump($datalist);